package com.example.first.thread;

/**
 * @Author LSQ
 * @Description TODO
 * @date 2021/8/29 9:37
 * @Version 1.0
 */

public class LearnVolatile1 {

    public volatile static boolean flag = false;
    // public static int age = 100;

    public static void changeFlag() {
        flag = true;
    }

    public static void main(String[] args) {
        Runnable runnable1 = () -> {
            changeFlag();
            String threadName = Thread.currentThread().getName();

        };

        Runnable runnable2 = () -> {
            String threadName = Thread.currentThread().getName();
            while (!flag) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(threadName + " running... ");
            }

            System.out.println(threadName + " stop... ");
        };

        // 这样加volatile依然没用， Task1设置了101，Task2依然可能读到是100
        Thread thread2 = new Thread(runnable2, "Task2");
        thread2.start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread thread1 = new Thread(runnable1, "Task1");
        thread1.start();


    }


}
